<template>
  <div class="enter-account">
    <div class="content-title">
      <span class="enterAccount">{{ $t("module.userCenter.title") }}</span>
      <Icon class="iconAccount" @click="step" type="ios-close" size="40" />
    </div>
    <div class="content-main">
      <div class="hint">{{ $t("module.userCenter.account") }}</div>
      <Form :model="modelForm" ref="editForm" class="ivu-form-no-margin-bottom" :rules="rule" :label-width="0">
        <Form-item prop="tenantCode">
          <Select
            v-model="modelForm.tenantCode"
            :placeholder="$t('module.userCenter.selectTenant')"
            size="large"
            :transfer="true"
            filterable
            filter-by-label
            clearable
          >
            <Option
              v-for="tenant in tenantList"
              :value="tenant.tenantCode"
              :key="tenant.tenantCode"
              :label="tenant.tenantName"
              >{{ tenant.tenantName }}</Option
            >
          </Select>
        </Form-item>
        <Form-item prop="account">
          <Input
            v-model="modelForm.account"
            :placeholder="$t('module.userCenter.account')"
            size="large"
            :maxlength="50"
          />
        </Form-item>
        <FormItem prop="captcha">
          <div style="display: flex;justify-content: space-between;align-items: center;">
            <Input
              v-model="modelForm.captcha"
              :placeholder="$t('module.userCenter.accountCode')"
              size="large"
              style="width: 374px;"
              :maxlength="6"
            />
            <img :src="captchaUrl" style="height: 36px;" @click="generateCaptchaUrl" v-show="captchaUrl" />
          </div>
        </FormItem>
        <FormItem class="button">
          <RPButton
            size="large"
            @click="next"
            style="width: 45%; borderradius: 0; height: 34px;"
            :text="$t('module.userCenter.next')"
          />
          <RPButton
            size="large"
            optType="text"
            style="width: 45%; borderradius: 0; height: 34px;"
            @click="step"
            :text="$t('module.userCenter.step')"
          />
        </FormItem>
      </Form>
    </div>
  </div>
</template>
<script>
import userCenter from "@lang/modules/userCenter";
import tenantAPI from "@/api/tenantApi.js";
import { RIPPLES_APP } from "@/const.js";
export default {
  name: "enter-account",
  components: {},
  props: {},
  locales: {
    "zh-CN": {
      module: {
        userCenter: userCenter["zh-CN"]
      }
    },
    "en-US": {
      module: {
        userCenter: userCenter["en-US"]
      }
    }
  },
  data() {
    return {
      modelForm: {
        tenantCode: "",
        account: "",
        captcha: ""
      },
      tenantList: [],
      rule: {
        tenantCode: [
          {
            required: true,
            message: this.$t("module.userCenter.selectTenant"),
            trigger: "change"
          }
        ],
        account: [
          {
            required: true,
            message: this.$t("module.userCenter.account"),
            trigger: "blur"
          }
        ],
        captcha: [
          {
            required: true,
            message: this.$t("module.userCenter.accountCode"),
            trigger: "blur"
          }
        ]
      },
      captchaUrl: ""
    };
  },
  computed: {},
  created: function() {
    this.initTenant();
    this.generateCaptchaUrl();
  },
  beforeMount: function() {},
  mounted: function() {},
  beforeDestroy: function() {},
  destroyed: function() {},
  methods: {
    // 初始化所属租户
    initTenant() {
      let param = {
        clientId: RIPPLES_APP,
        deleted: 0
      };
      tenantAPI.queryTenantListByAppId(param).then(data => {
        this.tenantList = data;
      });
    },
    // onTenantChange(value) {
    //   if (value) {
    //     this.generateCaptchaUrl();
    //   } else {
    //     this.captchaUrl = null;
    //   }
    // },
    next() {
      // 验证账号存在、验证码正确
      this.$refs["editForm"].validate(valid => {
        if (valid) {
          /*
          window.$http
            .post(
              `${window.RPConfig.userCenter}/user/getUserSecInfo` +
                "?account=" +
                this.modelForm.account +
                "&tenant=" +
                this.modelForm.tenantCode
            )
            .then(response => {
              // 如果是非自建用户不支持找回密码(用户类型：1 自建 2 第三方 3 云门户 4 LDAP)
              let data = response.data;
              if (data.type && data.type != 1) {
                let userType =
                  data.type == 2
                    ? this.$t("module.userCenter.thirdParty")
                    : data.type == 3
                    ? this.$t("module.userCenter.cloudPortal")
                    : data.type == 4
                    ? this.$t("module.userCenter.LDAP")
                    : "";
                const errMsg = userType
                  ? "“" + userType + "”" + this.$t("module.userCenter.unableRetrievePasswordTips")
                  : this.$t("module.userCenter.unableRetrievePasswordTips")
                this.$message.error({
                  // content: "“" + userType + "”" + this.$t("module.userCenter.unableRetrievePasswordTips"),
                  content: errMsg,
                  duration: 3
                });
              } else {
                window.$http
                  .post(
                    `${window.RPConfig.userCenter}/user/checkAccount` +
                      "?account=" +
                      this.modelForm.account +
                      "&captcha=" +
                      this.modelForm.captcha +
                      "&tenant=" +
                      this.modelForm.tenantCode
                  )
                  .then(response => {
                    if (response.data) {
                      this.$router.push({
                        name: "retrieve-password",
                        params: {
                          account: this.modelForm.account,
                          tenant: this.modelForm.tenantCode,
                          mobile: data.mobile,
                          email: data.email
                        }
                      });
                    } else {
                      this.$message.error({
                        content: this.$t("module.userCenter.validationTips"),
                        duration: 3
                      });
                    }
                  });
              }
            })
            .catch(() => {
              this.modelForm.captcha = "";
              this.generateCaptchaUrl();
            });
            */

          const { modelForm: { account, tenantCode, captcha } } = this;
          window.$http
            .post(
              `${window.RPConfig.userCenter}/user/checkAccountV2?account=${account}&captcha=${captcha}&tenant=${tenantCode}`
            )
            .then(res => {
              const data = res?.data;
              // 如果是非自建用户不支持找回密码(用户类型：1 自建 2 第三方 3 云门户 4 LDAP)
              const usrType = data?.type || "";
              const userTypeMap = {
                2: this.$t("module.userCenter.thirdParty"),
                3: this.$t("module.userCenter.cloudPortal"),
                4: this.$t("module.userCenter.LDAP")
              };
              if (usrType != 1) {
                const userType = userTypeMap[usrType] || "";
                this?.$message?.error({
                  content: `“${userType}”${this.$t("module.userCenter.unableRetrievePasswordTips")}`,
                  duration: 3
                });
                return;
              }

              if (data) {
                this.$router.push({
                  name: "retrieve-password",
                  params: {
                    account: account,
                    tenant: tenantCode,
                    mobile: data?.mobile || '',
                    email: data?.email || ''
                  }
                });
              } else {
                this.modelForm.captcha = "";
                this.generateCaptchaUrl();
                this?.$message?.error({
                  content: $t("module.userCenter.validationTips"),
                  duration: 3
                });
              }
            })
            .catch(() => {
              this.modelForm.captcha = "";
              this.generateCaptchaUrl();
            });
        }
      });
    },
    step() {
      const type = window.RPConfig.logintype;
      if (type === "cas") {
        window.location.href = window.RPConfig.cas_logout + "?service=" + window.location.origin;
      } else if (type === "single") {
        this.$router.push({ path: "/login" });
      } else {
        window?.$util?.redirectToLogin()
      }
    },
    generateCaptchaUrl() {
      this.captchaUrl = `${window.RPConfig.userCenter}/captcha?${Math.random()}`;
    }
  },
  watch: {},
  directives: {}
};
</script>
<style lang="less">
@import "./forgotPassword.less";
</style>
